package xyz.ieden.freemarker.resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import xyz.ieden.freemarker.entity.User;
import xyz.ieden.freemarker.servlet.IUserServlet;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Gavin on 2017.09.09.
 */
@Controller
@RequestMapping(value = "user")
public class UserResource {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class);

    @Autowired(required = false)
    private IUserServlet userServlet;


    @GetMapping(value = "{userId}", produces = MediaType.TEXT_HTML_VALUE)
    public String getUserById(@PathVariable("userId")Long userId, HttpServletRequest request, Model model) {
        LOGGER.info("用户请求 ip：" + request.getRemoteAddr());
        User user = userServlet.getUserById(userId);
        model.addAttribute("user", user);
        return "user";
    }

    @GetMapping(value = "", produces = MediaType.TEXT_HTML_VALUE)
    public String getAllUser(HttpServletRequest request, Model model) {
        LOGGER.info("用户请求 ip：" + request.getRemoteAddr());
        List<User> userList = userServlet.getAllUser();
        LOGGER.info("用户数量：{}", userList.size());
        model.addAttribute("userList", userList);
        return "userList";
    }
}
